import { ofetch } from 'ofetch'

const createApi = () => {
  const api = ofetch.create({
    baseURL: import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080/api/',
    // baseURL: import.meta.env.VITE_API_BASE_URL || 'http://118.25.104.139:8080/api/',
    async onRequest({ options }) {
      const accessToken = useCookie('accessToken').value
      if (accessToken) {
        options.headers = {
          ...options.headers,
          Authorization: `Bearer ${accessToken}`,
        }
      }
    },
  })

  const createRequest = async (endpoint, method = 'GET', data = {}) => {
    try {
      const res = await api(endpoint, {
        method,
        body: method !== 'GET' ? data : undefined,
        onResponseError({ response }) {
          errors.value = response._data.errors
        },
      })
      return res
    } catch (error) {
      console.error(error)
    }
  }

  return {
    get: async (endpoint, data = {}) => createRequest(endpoint, 'GET', data),
    post: async (endpoint, data = {}) => createRequest(endpoint, 'POST', data),
  }
}

export const $ivyApi = createApi()
